import axios from 'axios';
import {Toast} from 'vant';
import Cookie from './cookie';
import AesGcm from "@/utils/aesgcm";

axios.defaults.withCredentials = true;
axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8';

async function ajax(url, type, params, formSubmit) {
  const headers = {
    aitalk_token: Cookie.getCookie('aitalk_token_zh') || '',
    visit_type: 'MOA'
  };
  if(formSubmit === "formSubmit"){
    headers['Content-Type'] = 'multipart/form-data';
  }else if(formSubmit === "form-urlencoded"){
    headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
  }
  const result = await axios({
    method: type,
    url: AesGcm.decrypt(process.env.VUE_APP_INTERFACE_URL) + url,
    timeout: 30000,
    headers: headers,
    params: type === 'get' ? params : null,
    data: params
  });
  let msg = '系统打盹了，休息一会。';
  if (result) {
    const data = result.data;
    const code = data.result;
    //接口调用成功
    if (code === '1' || data.success){
      return data;
    }
    //接口调用出错，如：没有做身份认证
    msg = data.message || msg;
    if (msg === 'token认证失败！' ){
      msg = '身份认证中...';
      location.replace(AesGcm.decrypt(process.env.VUE_APP_JUMP_URL));
    }
  }
  Toast.fail({
    message: msg,
    duration: 2 * 1000
  });
}
const api = {
  get(url, params) {
    return ajax(url, 'get', params);
  },
  post(url, params) {
    return ajax(url, 'post', params);
  },
  formSubmit(url, params) {
    return ajax(url, 'post', params, "formSubmit");
  },
  formUrlencoded(url, params) {
    return ajax(url, 'post', params, "form-urlencoded");
  }
};

export default api;
